//
//  RACCommand+KLAutoEnable.m
//  KoalaUtilKit
//
//  Created by Tommy on 15/1/20.
//  Copyright (c) 2015年 Koala Team. All rights reserved.
//

#import "ReactiveCocoa.h"
#import "RACCommand+KLAutoEnable.h"
#import <objc/runtime.h>

static char klAutoEnableKey;


@implementation RACCommand (KLAutoEnable)
+ (RACCommand *)kl_autoCmdWithSignalBlock:(RACSignal *(^)(id))signalBlock{
    return [[RACCommand alloc]initAutoWithSignalBlock:signalBlock];
}

- (BOOL)klEnable{
    NSNumber* enable = objc_getAssociatedObject(self, &klAutoEnableKey);
    return [enable boolValue];
}

- (void)setKlEnable:(BOOL)klEnable{
    [self willChangeValueForKey:@"klEnable"];
    objc_setAssociatedObject(self, &klAutoEnableKey, @(klEnable), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:@"klEnable"];
}

- (instancetype)initAutoWithSignalBlock:(RACSignal *(^)(id))signalBlock{
    
    return [self initWithSignalBlock:signalBlock];
    
    
    self.klEnable = YES;
    return [self initWithEnabled:[RACObserve(self, klEnable) startWith:@(YES)]signalBlock:^RACSignal *(id input) {
        RACSignal *signal = signalBlock(input) ;
        return [[signal initially:^{
            self.klEnable = NO;
        }]finally:^{
            self.klEnable = YES;
        }];        
    }];

}


@end
